package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;

import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息:{}", setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {

        //分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtopage = new Page<>();
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        //添加查询条件,根据name进行like模糊查询
        queryWrapper.like(name != null, Setmeal::getName, name);

        //添加排序条件,根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo, queryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(pageInfo, dtopage, "records");

        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item, setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //分类名称
                String categoryname = category.getName();
                setmealDto.setCategoryName(categoryname);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        dtopage.setRecords(list);
        return R.success(dtopage);
    }

    /**
     * 删除套餐
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    /**
     * 起售,停售,批量起售,批量停售
     */
    @PostMapping("status/{status}")
    public R update(@PathVariable Integer status, @RequestParam List<Long> ids) {
        for (Long id : ids) {
            Setmeal setmeal = new Setmeal();
            setmeal.setId(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("操作成功");
    }

    /**
     * 根据id查询套餐
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id) {
        //根据套餐ID查询套餐数据
        Setmeal setmeal = setmealService.getById(id);

        //根据套餐id查询套餐对应的菜品数据
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);

        List<SetmealDish> list = setmealDishService.list(queryWrapper);
        //将套餐setmeal 和套餐菜品集合 setmealDishList 数据封装到Dto并返回
        //首先new一个SetmealDto对象
        SetmealDto setmealDto = new SetmealDto();
        //BeanUtils.copyProperties()拷贝setmeal到setmealDto中
        BeanUtils.copyProperties(setmeal, setmealDto);
        //将setmealDishList 设置到 setmealDto中
        setmealDto.setSetmealDishes(list);
        //返回setmealDto
        return R.success(setmealDto);


    }

    /**
     * 修改菜品
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody SetmealDto setmealDto) {
        //1、根据id更新 setmeal 套餐表数据 update setmeal set xx=?,.. where id =?
        Setmeal setmeal = setmealService.getById(setmealDto);

        //2、操作套餐对应的菜品数据： setmeal_dish
       Long id = setmealDto.getId();
       LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(SetmealDish::getId,id);
        //2.1 先根据套餐id删除套餐对应的菜品数据： delete from setmeal_dish where setmeal_id =?
        setmealDishService.remove(queryWrapper);
        // 获取套餐id   setmealDto.getId()
        // 使用 setmealDishMapper 根据套餐id进行删除 ：delete from setmeal_dish where setmeal_id =?
        //2.2 重新添加新的套餐对应的菜品数据 insert setmeal_dish values (..)
        // setmealDto.getSetmealDishes() 获取套餐的菜品集合 List<SetmealDish>
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        // 遍历套餐菜品集合数据
        for (SetmealDish setmealDish : setmealDishes) {
            // 有没有数据需要set ： 设置套餐id  setSetmealId
            setmealDish.setSetmealId(id);
        }


        // 添加套餐菜品数据 insert
        setmealDishService.saveBatch(setmealDishes);

        return R.success("修改成功");
    }
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal>list = setmealService.list(queryWrapper);
        return R.success(list);
    }
}
